<template>
    <div>
        <div style="margin-top: 15px;" v-show='setBtnState'>
            <Button type="primary" class="md-add-jh" @click='addTaskBtn'>添加任务</Button>
            <Poptip
                confirm
                title="确定要同步导调任务吗？"
                transfer @on-ok="ynchTaskBtn"
                word-wrap>
                <Button type="primary" :loading='modelLoading2'>同步导调任务</Button>
            </Poptip>
            <Poptip
                confirm
                title="确定要清空训练吗？"
                transfer @on-ok="clearTrain"
                word-wrap>
                <Button type="error" :loading='clearBtnLoading'>清空训练</Button>
            </Poptip>
        </div>
        <Table :columns="taskCol" :data="taskList" style="margin-top: 15px;"></Table>
        <div style="display: flex;justify-content: center;margin: 15px 0">
            <Page :total=taskTotal :page-size="pageSize" :current="page" show-total show-elevator @on-change="taskChangePage"/>
        </div>
        <!-- 新建/修改 任务 -->
        <Modal
            v-model="taskModel" width="600"
            :mask-closable="false"
            :footer-hide="true"
            :title="title">
            <Form ref="formV" :model="formV" :rules="formVRule" :label-width="80" >
                <FormItem label="名称" prop="name">
                    <Input v-model.trim="formV.name" placeholder="请输入任务名称"></Input>
                </FormItem>
                <FormItem label="任务顺序" prop="taskOrder">
                     <InputNumber :min='1' v-model="formV.taskOrder" :editable="false"></InputNumber>
                </FormItem>
                <FormItem label="难易程度" prop="level">
                    <RadioGroup v-model="formV.level">
                        <Radio label="simple">简单</Radio>
                        <Radio label="middle">中等</Radio>
                        <Radio label="hard">困难</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="提交内容类型" prop="commitType">
                    <RadioGroup v-model="formV.commitType">
                        <Radio label="input">简单文本</Radio>
                        <Radio label="richText">富文本</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="分值" prop="score">
                    <InputNumber :max='300' :min='0' v-model="formV.score" :step="1"></InputNumber>
                </FormItem>
                <FormItem label="提交内容长度" prop="userCommitLimit">
                    <InputNumber :max='255' :min='0' v-model="formV.userCommitLimit" :step="1"></InputNumber>
                    <p style="color:#ff9900;font-size:10px;line-height: 2;">
                        <Icon type="ios-information-circle-outline"/>
                        如果为0则表示不限制长度
                    </p>
                </FormItem>
                
                <FormItem label="内容"  prop="content">
                    <quill-editor
                        v-model.trim="formV.content"
                        class="editor"
                        ref="myQuillEditor"
                        :options="editorOption"
                        @blur="onEditorBlur($event)"
                        @focus="onEditorFocus($event)"
                        @change="onEditorChange($event)">
                    </quill-editor>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="submitBtn('formV')" :loading='modelLoading'>确定</Button>
                    <Button @click="resetBtn('formV')" style="margin-left: 8px">重置</Button>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
    import {creatTask,taskList,modifyTask,delTask,autoAddTask,clearAutoTask,processNodeData,getGroupData,processData,clearProcess} from '@/api/train.js'
    import expandRow from './taskContent.vue';
    import Quill from 'quill'
    import { quillEditor} from "vue-quill-editor"; // 调用编辑器
    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.snow.css'
    import 'quill/dist/quill.bubble.css'
    import { escape2Html } from '@/libs/utils'

    const toolbarOptions = [
        ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
        ["blockquote", "code-block"], // 引用  代码块
        [{ header: 1 }, { header: 2 }], // 1、2 级标题
        [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
        [{ script: "sub" }, { script: "super" }], // 上标/下标
        [{ indent: "-1" }, { indent: "+1" }], // 缩进
        // [{'direction': 'rtl'}],                         // 文本方向
        [{ size: ["small", false, "large", "huge"] }], // 字体大小
        [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
        [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
        [{ align: [] }], // 对齐方式
        ["clean"], // 清除文本格式
        // ['link',"image"] // 链接、图片、视频
    ];
    export default {
        components: {
            quillEditor,
        },
        props:['hidebtn','isImport'],
        data () {
            const validateOrder = (rule, value, callback)=>{
                if(value.length <= 0){
                    callback(new Error('请设置任务顺序'));
                }else{
                    callback();
                }
            }
            const validateScore = (rule, value, callback)=>{
                let v = parseInt(value)
                if(v < 0){
                    callback(new Error('任务分值不能为负数'));
                }else if(v > 300){
                    callback(new Error('任务分值范围为0—300'));
                }else{
                    callback();
                }
            }
            const validateCommit = (rule, value, callback)=>{
                let v = parseInt(value)
                if(v < 0){
                    callback(new Error('长度不能为负数'));
                }else if(v > 255){
                    callback(new Error('范围为0—255'));
                }else{
                    callback();
                }
            }
            return {
                setBtnState:'',
                sceneID:this.$route.query.id,
                testId:this.$route.query.testId,
                isImp:'',
                // 任务
                taskTotal:0,
                taskCol:[
                    {
                        type: 'expand',
                        width: 60,
                        render: (h, params) => {
                            return h(expandRow, {
                                props: {
                                    row: params.row
                                }
                            })
                        }
                    },
                    {
                        title:'名称',
                        key:'name',
                        align:'center'
                    },
                    {
                        title:'任务顺序',
                        key:'taskOrder',
                        align:'center'
                    },
                    {
                        title:'任务类型',
                        key:'taskType',
                        align:'center',
                        render: (h, params) => {
                            return h('div','训练任务')
                        }
                    },
                    {
                        title:'提交内容长度限制',
                        key:'userCommitLimit',
                        align:'center',
                        render: (h, params) => {
                            if(params.row.userCommitLimit === 0){
                                return h('div','无长度限制')
                            }else{
                                return h('div',params.row.userCommitLimit)
                            }
                        }
                    },
                    {
                        title:'提交形式',
                        key:'commitType',
                        align:'center',
                        render: (h, params) => {
                            if(params.row.commitType === 'input'){
                                return h('div','简单文本')
                            }else if(params.row.commitType === 'richText'){
                                return h('div','富文本')
                            }
                        }
                    },
                    {
                        title:'难易程度',
                        key:'level',
                        align:'center',
                        render: (h, params) => {
                            let text = ''
                            if(params.row.level === 'simple'){
                                text = '简单'
                            }else if(params.row.level === 'middle'){
                                text = '中等'
                            }else if(params.row.level === 'hard'){
                                text = '困难'
                            }
                            return h('div',text)
                        }
                    },
                    {
                        title:'分值',
                        key:'score',
                        align:'center'
                    },
                    {
                        title:'创建者',
                        key:'creatorName',
                        align:'center'
                    },
                    {
                        title:'创建时间',
                        key:'createTime',
                        align:'center'
                    },
                    {
                        title:'操作',
                        key:'action',
                        align:'left',
                        width:200,
                        render:(h,params)=>{
                            let flag = this.setBtnState
                            return h('a',{
                                attrs: {
                                    disabled:flag?false:true,
                                },
                                style: {
                                    'display': 'flex',
                                    'justify-content': 'flex-start',
                                    'align-items': 'center',
                                },
                            },[
                                h('Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            transfer:true,
                                            title: '确定要删除这个任务吗？'
                                        },
                                        on: {
                                            'on-ok': ()=>{
                                                this.delTask(params.row)
                                            },
                                            'on-cancel': ()=>{

                                            }
                                        }
                                    },
                                    [
                                        h('img', {
                                            attrs: {
                                                src: flag?require('../../../assets/project/delNote-h.png'):require('../../../assets/project/delNote-d.png'),
                                            },
                                            style: {
                                                cursor: 'pointer',
                                                'margin-right':'5px',
                                                'vertical-align': 'middle',
                                                width:'16px',
                                                height:'16px',
                                                display:'inline-block',
                                            },
                                        }),
                                    ],
                                ),
                                h('div', {
                                    on: {
                                        'click': ()=>{
                                            this.modifyTask(params.row)
                                        },
                                    },
                                    style:{
                                        'margin-left':'15px',
                                    }
                                }, [
                                    h('img', {
                                        attrs: {
                                            src: flag?require('../../../assets/project/modifys-h.png'):require('../../../assets/project/modifys.png'),
                                        },
                                        style: {
                                            cursor: 'pointer',
                                            'margin-right':'5px',
                                            'vertical-align': 'middle',
                                            width:'16px',
                                            height:'16px',
                                            display:'inline-block',
                                        },
                                    }),
                                ])
                            ])
                        }
                    }
                ],
                taskList:[],
                page:1,
                pageSize:10,
                // 添加
                taskModel:false,
                modelLoading:false,
                isCreat:true,
                title:'创建任务',
                formV:{
                    "description": "",
                    "name": "",
                    "content": "",
                    taskOrder:1,
                    score:0,
                    level:'simple',
                    userCommitLimit:0,
                    commitType:'input',
                },
                formVRule:{
                    name: [
                        { required: true,min:1,max: 64, message: '名称长度为1—64个字符', trigger: 'change' },
                    ],
                    taskOrder: [
                        { required: true,validator: validateOrder,},
                    ],
                    score: [
                        { required: true,validator: validateScore,},
                    ],
                    userCommitLimit: [
                        { required: true,validator: validateCommit,},
                    ],
                    level: [
                        { required: true,trigger: 'change',message: '请选择难度'},
                    ],
                    commitType: [
                        { required: true,trigger: 'change',message: '请选择内容文本类型'},
                    ],
                    content: [
                        { required: true,min:1,max: 200, message: ''}
                    ],
                },
                modifyTaskId:'',
                // 富文本编辑器设置
                editorOption: {
                    placeholder: '请输入任务内容', //提示
                    modules: {
                        toolbar: {
                            container:toolbarOptions,//工具菜单栏配置
                        },
                    },
                },
                // 同步导调任务
                modelLoading2:false,
                clearBtnLoading:false,
            }
        },
        created(){
            
        },
        mounted(){
            this.getTaskList()
        },
        watch: {
            hidebtn(newVal) {
                this.setBtnState = newVal //对父组件传过来的值进行监听，如果改变也对子组件内部的值进行改变
            },
            isImport(newVal) {
                this.isImp = newVal //对父组件传过来的值进行监听，如果改变也对子组件内部的值进行改变
            },
        },
        methods:{
            // 任务列表
            getTaskList(){
                this.setBtnState = this.hidebtn
                this.isImp = this.isImport
                let params = {
                    pageIndex:this.page,
                    pageSize:this.pageSize,
                    trainingId:this.sceneID,
                }
                taskList(params)
                .then(res=>{
                    if(res.data.code === 1){
                        this.taskList = res.data.data.records
                        this.taskTotal = res.data.data.total
                        this.formV.taskOrder = this.taskTotal+1
                    }else{
                        this.taskList = []
                        this.taskTotal = 0
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            taskChangePage(val){
                this.page = val
                this.getTaskList()
            },
            // 添加任务
            addTaskBtn(){
                this.title = '创建任务'
                this.isCreat = true
                this.taskModel = true
                this.formV.name = ''
                this.formV.content = ''
                this.formV.score = 0
                this.formV.level = 'simple'
                this.formV.userCommitLimit = 0
            },
            submitBtn(name){
                if(this.isCreat){
                    this.creatSub(name)
                }else{
                    this.modifySub(name)
                }   
            },
            // 重置按钮
            resetBtn(name){
                this.$refs[name].resetFields();
            },
            // 创建提交
            creatSub(name){
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        let params = {
                            "description": this.formV.description,
                            "name": this.formV.name,
                            "trainingId": this.$route.query.id,
                            "testId": this.testId,
                            "content": this.formV.content,
                            "level": this.formV.level,
                            "score": parseInt(this.formV.score),
                            userCommitLimit: parseInt(this.formV.userCommitLimit),
                            taskOrder:this.formV.taskOrder,
                            commitType:this.formV.commitType,
                        }
                        this.modelLoading = true
                        creatTask(params)
                            .then(res=>{
                                if(res.data.code == 1){
                                   this.$Message.success({
                                       content:'创建成功',
                                       duration:3,
                                   })
                                   this.taskModel = false
                                   this.getTaskList()
                                }else {
                                    this.$Message.error({
                                       content:res.data.message,
                                       duration:5,
                                   })
                                }
                                this.modelLoading = false
                            })
                            .catch(err=>{
                                this.modelLoading = false
                                this.$Message.error('服务器连接失败！')
                            })
                    }else {
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            // 修改任务
            modifyTask(row){
                this.modifyTaskId = row.id
                this.formV = {
                    "description": row.description,
                    "name": row.name,
                    "level": row.level,
                    "score": parseInt(row.score),
                    userCommitLimit: parseInt(row.userCommitLimit),
                    "content": escape2Html(row.content),
                    taskOrder:parseInt(row.taskOrder),
                    commitType:row.commitType,
                }
                this.title = '修改任务'
                this.isCreat = false
                this.taskModel = true
            },
            // 修改提交
            modifySub(name){
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        let params = {
                            "description": this.formV.description,
                            "name": this.formV.name,
                            "trainingId": this.$route.query.id,
                            "testId": this.testId,
                            "content": this.formV.content,
                            'id':this.modifyTaskId,
                            "level": this.formV.level,
                            "score": parseInt(this.formV.score),
                            userCommitLimit: parseInt(this.formV.userCommitLimit),
                            taskOrder:this.formV.taskOrder,
                            commitType:this.formV.commitType,
                        }
                        this.modelLoading = true
                        modifyTask(params)
                            .then(res=>{
                                if(res.data.code == 1){
                                   this.$Message.success({
                                       content:'创建成功',
                                       duration:3,
                                   })
                                   this.taskModel = false
                                   this.getTaskList()
                                }else {
                                    this.$Message.error({
                                       content:res.data.message,
                                       duration:5,
                                   })
                                }
                                this.modelLoading = false
                            })
                            .catch(err=>{
                                this.modelLoading = false
                                this.$Message.error('服务器连接失败！')
                            })
                    }else {
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            // 删除任务
            delTask(row){
                delTask(row.id)
                .then(res=>{
                    if(res.data.code == 1){
                        this.$Message.success({
                            content:'删除成功',
                            duration:3,
                        })
                        this.getTaskList()
                    }else{
                        this.$Message.error({
                            content:res.data.message,
                            duration:5,
                        })
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            // 编辑器
            onEditorBlur(e){
                let content = e.root.textContent
                if(content.length <= 0 || content.length > 200 || content == null || content == undefined ){
                    this.formVRule.content[0].message = '名称长度为1—200个字符'
                }else{
                    this.formVRule.content[0].message = ''
                }
            }, // 失去焦点事件
            onEditorFocus(){}, // 获得焦点事件
            onEditorChange(){}, // 内容改变事件
            // 同步导调任务
            ynchTaskBtn(){
                let params = {
                    testId:this.testId,
                    trainId:this.sceneID,
                }
                this.modelLoading2 = true
                processData(params)
                    .then(res=>{
                        if(res.data.code == 1){
                            this.$Message.success({
                                content:'操作成功',
                                duration:3,
                            })
                            this.getTaskList()
                        }else {
                            this.$Message.error({
                                content:res.data.message,
                                duration:5,
                            })
                        }
                        this.modelLoading2 = false
                    })
                    .catch(err=>{
                        this.modelLoading2 = false
                        this.$Message.error('服务器连接失败！')
                    })
            },
            // 清空训练
            clearTrain(){
                this.clearBtnLoading = true
                clearProcess(this.sceneID)
                .then(res=>{
                    if(res.data.code === 1){
                        this.getTaskList()
                        this.$Message.success({
                            content:'清空成功',
                            duration:3,
                        })
                    }else{
                        this.$Message.error({
                            content:res.data.message,
                            duration:5,
                        })
                    }
                    this.clearBtnLoading = false
                })
                .catch(err=>{
                    console.log(err)
                })
            },
        }
    }
</script>
<style scoped>
    .editor .ql-container.ql-snow{
    	overflow: hidden auto;
    }
    .editor .ql-editor{
    	overflow:auto;
    }
</style>

